<!--投票-->
<script setup>
import {ref, toRefs} from "vue";
import {useStore} from "vuex";
import {formatDate} from "@ginstone/common-utils/dist/src/utils/DateUtils";
import {VoteResult} from "@ginstone/nga-api/dist/src/enums/VoteResult";
import {VoteType} from "@ginstone/nga-api/dist/src/enums/VoteType";
import {setupMapGetters} from "@/assets/js/vuexUtils";
import {ElMessageBox} from "element-plus";
import {SuperVoteData} from "@ginstone/nga-api/dist/src/response/vote/Vote";
import {NukeApi} from "@ginstone/nga-api/dist/src/method/NukeApi";
import {VoteParam} from "@ginstone/nga-api/dist/src/params/NukeParams";
import {ElementUtils} from "@/assets/js/ElementUtils";

const props = defineProps({
  data: {type: SuperVoteData, required: true},
  topicId: {type: Number, required: true},
})
const emit = defineEmits(['refresh'])
const store = useStore();
const {data, topicId} = toRefs(props)
const getClient = setupMapGetters("Account", ["getClient"]).getClient.value


const selection = ref();
// 多选框变化
const handleSelectionChange = (e) => {
  selection.value = e
}
// 投票按钮是否禁用
const voteDisable = (sel, data) => {
  if (!sel || sel.length === 0) {
    return true;
  }
  if (data.maxSelect && sel.length > data.maxSelect) {
    return true;
  }
  return false;
}
// 投票是否开放(没有截止时间，或未到截止时间)
const isOpen = (data) => !data.end || new Date() < data.end

// 是否可以投票
const voteAble = (data) => {
  return data.type === VoteType.VOTE && isOpen(data)
}
// 投票请求
const vote = () => {
  const labels = selection.value.map(i => i.label).join(", ")
  const content = `您选择投票给: [ ${labels} ]`
  ElementUtils.confirm(content, "确认").then(() => {
    NukeApi.vote(getClient(), new VoteParam(topicId.value, selection.value.map(i => i.id))).then(res => {
      console.log(res)
      emit("refresh")
      //todo 成功消息不确定
      ElementUtils.notice({message: res})
    }).catch(ElementUtils.exceptionHandler)
  }).catch(e => {
    console.warn(e)
  })
}

// 是否可以投注
const betAble = (data) => {
  return data.type === VoteType.BET && !data.successId && isOpen(data)
}
// 投注请求
const bet = (option) => {
  const min = data.value.min ? data.value.min : ''
  const max = data.value.max ? data.value.max : ''
  const text = `您选择投注: [${option.label}], 请输入投注金额(${min} ~ ${max}):`

  ElMessageBox.prompt(text, '投注', {
    inputValue: min,
    inputType: "number",
    inputValidator: (value) => {
      if (!value) {
        return false;
      }
      if (min && value < min) {
        return false;
      }
      if (max && value > max) {
        return false;
      }
      return true;
    },
    inputErrorMessage: '请输入指定范围的金额',
  }).then(({value}) => {
    NukeApi.vote(getClient(), new VoteParam(topicId.value, [option.id, value])).then(res => {
      console.log(res)
      emit("refresh")
      //todo 成功消息不确定
      ElementUtils.notice({message: res})
    }).catch(ElementUtils.exceptionHandler)
  }).catch(e => {
    console.warn(e)
  })
}
</script>

<template>
  <div id="vote-data">
    <h4 style="margin-top: 3px;margin-bottom: 3px">{{ data.type }}</h4>
    <div v-if="betAble(data)">点击选项投注</div>
    <div>
      <div id="vote-options">
        <el-table :data="data.options" @selection-change="handleSelectionChange">
          <el-table-column v-if="voteAble(data)" type="selection" width="55"/>
          <el-table-column label="选项">
            <template #default="{row}">
              <el-button v-if="betAble(data)" class="clickable" size="small" type="primary" @click="bet(row)">{{ row.label }}</el-button>
              <span v-else>{{ row.label }}</span>
              <el-tag v-if="data.hasOwnProperty('successId') && data.successId===row.id" effect="dark" type="danger">胜出</el-tag>
            </template>
          </el-table-column>
          <el-table-column :label="data.type===VoteType.VOTE?'票数':'人数'">
            <template #default="{row}">
              <span class="vote-count">{{ row.count }}</span>
              <span>({{ Math.floor(row.countPer * 10000) / 100 }}%)</span>
            </template>
          </el-table-column>
          <el-table-column v-if="data.type===VoteType.BET" label="金额">
            <template #default="{row}">
              <span class="vote-count">{{ row.money }}</span>
              <span>({{ Math.floor(row.moneyPer * 10000) / 100 }}%)</span>
            </template>
          </el-table-column>

        </el-table>
      </div>
      <div v-if="voteAble(data)">
        <el-button :disabled="voteDisable(selection,data)" type="primary" @click="vote">投票</el-button>
      </div>
      <div id="vote-tips">
        <span v-if="data.end" class="bold">结束时间： {{ formatDate(data.end, 'yy-MM-dd hh:mm') }}
          <el-tag v-if="data.end < new Date()" effect="dark" type="danger">已结束</el-tag>
        </span>
        <span v-if="data.result">
          <template v-if="data.result===VoteResult.AFTER_VOTE">投票 后展示结果</template>
          <template v-if="data.result===VoteResult.AFTER_END">结束后展示结果</template>
        </span>
        <div v-if="isOpen(data)">
          <span class="bold">要求：</span>
          <span v-if="data.maxSelect">最多选择 {{ data.maxSelect }} 项</span>
          <span v-if="data.reputation">版面声望至少 {{ data.reputation }}</span>
          <span v-if="data.min">最少 {{ data.min }} 铜币</span>
          <span v-if="data.max">最大 {{ data.max }} 铜币</span>
        </div>
        <div v-if="data.totalCount">
          <span class="bold">统计：</span>
          <span>参与人数: {{ data.total }}</span>
          <span v-if="data.type===VoteType.VOTE">总票数: {{ data.totalCount }}</span>
          <span v-if="data.totalMoney">总投注数: {{ data.totalMoney }} 铜币</span>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
#vote-tips span {
  margin-right: 5px;
}

#vote-tips ul {
  margin-top: 2px;
  margin-bottom: 2px;
}

#vote-data {
  margin: 10px;
}

.vote-count {
  font-weight: bold;
  margin-right: 3px
}
</style>